package com.hnluchuan.staff.service;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.hnluchuan.staff.dao.RulesDAO;
import com.hnluchuan.staff.model.Rules;
import com.hnluchuan.staff.dto.RulesDTO;
import com.hnluchuan.core.support.Page;
import com.hnluchuan.utils.common.BeanMapper;

@Service
public class RulesService extends BaseService {
	
	@Autowired
	private RulesDAO rulesDAO;
	
	public List<RulesDTO> find(RulesDTO query, Page page) {
		List<Rules> models = rulesDAO.find(query, page);
		List<RulesDTO> dtos = toDTOs(models);
		return dtos;
	}
	
	public List<RulesDTO> findAll() {
		return this.find(new RulesDTO(), null);
	}
	
	public List<RulesDTO> findAll(RulesDTO query) {
		return this.find(query, null);
	}
	
	public List<RulesDTO> find(Page page) {
		return this.find(new RulesDTO(), page);
	}
	
	public List<RulesDTO> find(int count) {
		Page page = new Page();
		page.setPage(1);
		page.setPageSize(count);
		return this.find(new RulesDTO(), page);
	}
	
	public Long create(RulesDTO dto) {
		Rules model = new Rules();
		toModel(model, dto);
		return rulesDAO.create(model);
	}
	
	public RulesDTO load(Long id) {
	    Rules model = rulesDAO.load(id);
	    return toDTO(model);
    }

	public void updateAllFields(RulesDTO dto) {
		Rules model = rulesDAO.load(dto.getId());
		toModel(model, dto);
		rulesDAO.update(model);
    }

	public void deleteByIds(Long[] ids) {
		throw new RuntimeException("默认禁止删除，请确认是物理删除还是逻辑删除");
		/*
		if (ids != null) {
			for (Long id : ids) {
				rulesDAO.deleteById(id);
			}
		} */
    }
	
	public void deleteById(Long id) {
		this.deleteByIds(new Long[] {id});
	}

	public RulesDTO findOne(RulesDTO query) {
		Rules model = rulesDAO.findOne(query);
		return toDTO(model);
	}
	
	private List<RulesDTO> toDTOs(List<Rules> models) {
		if (CollectionUtils.isEmpty(models)) {
			return new ArrayList<RulesDTO>(0);
		}
		List<RulesDTO> dtos = new ArrayList<RulesDTO>(models.size());
		for (Rules model : models) {
	        RulesDTO dto = toDTO(model);
	        dtos.add(dto);
        }
	    return dtos;
    }
    
    private RulesDTO toDTO(Rules model) {
		if (model == null) {
			return null;
		}
		RulesDTO dto = BeanMapper.map(model, RulesDTO.class);
		
		return dto;
	}
	
	private void toModel(Rules model, RulesDTO dto) {
		BeanMapper.copy(dto, model);
    }
	
	@SuppressWarnings("unused")
	private List<Rules> toModels(List<RulesDTO> dtos) {
		if (CollectionUtils.isEmpty(dtos)) {
			return new ArrayList<Rules>(0);
		}
		List<Rules> models = new ArrayList<Rules>(dtos.size());
		for (RulesDTO dto : dtos) {
	        Rules model = new Rules();
	        toModel(model, dto);
	        models.add(model);
        }
		return models;
	}
}
